package com.novellotus.iov.carvice.retrofit;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.ActivityEvent;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Rich on 2017/8/3.
 */

public class RxSchedulers {


    /**
     * @param rxLifecycle
     * @param <T>生命周期
     * @return
     */
    public static <T> LifecycleTransformer<T> lifecycle(LifecycleProvider<ActivityEvent> rxLifecycle)  {
        return rxLifecycle.bindUntilEvent(ActivityEvent.DESTROY);
    }

    /**
     * @param <T>
     * @return
     * 在子线程处理事务，在主线程处理观察事件
     */
    public static <T> ObservableTransformer<T, T> compose() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> observable) {
                return observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * @param <T>
     * @return
     * 异步
     */
    public static <T> ObservableTransformer<T, T> composeIo() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> observable) {
                return observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io());
            }
        };
    }
}
